<template>
  <div class="profile-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>我的资料 </span>
      </div>

      <!-- 头像 + 基础信息 -->
      <el-row :gutter="20">
        <el-col :span="6" style="text-align: center">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/file/upload'"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :headers="uploadHeaders"
          >
            <img v-if="user.avatar" :src="user.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; color: #999; font-size: 12px">
            点击更换头像
          </div>
        </el-col>

        <el-col :span="18">
          <el-form label-width="100px" size="small">
            <el-form-item label="用户名">
              <span v-if="!editMode">{{ user.username }}</span>
              <el-input v-else v-model="form.username" style="width: 220px" />
            </el-form-item>

            <el-form-item label="手机号">
              <span v-if="!editMode">{{ user.phoneNumber }}</span>
              <el-input
                v-else
                v-model="form.phoneNumber"
                style="width: 220px"
              />
            </el-form-item>

            <el-form-item label="个人介绍">
              <span v-if="!editMode">{{ user.content || "-" }}</span>
              <el-input
                v-else
                v-model="form.content"
                type="textarea"
                :rows="3"
                style="width: 400px"
              />
            </el-form-item>

            <el-form-item label="注册时间">
              <span>{{ user.createTime | date }}</span>
            </el-form-item>

            <el-form-item label="上次登录">
              <span>{{ user.loginTime | date }}</span>
            </el-form-item>

            <el-form-item>
              <template v-if="!editMode">
                <el-button type="primary" size="small" @click="enterEdit"
                  >编辑资料</el-button
                >
                <el-button size="small" @click="showPwdDlg = true"
                  >修改密码</el-button
                >
              </template>
              <template v-else>
                <el-button type="primary" size="small" @click="saveProfile"
                  >保存</el-button
                >
                <el-button size="small" @click="cancelEdit">取消</el-button>
              </template>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="showPwdDlg"
      width="420px"
      @closed="resetPwdForm"
    >
      <el-form
        ref="pwdForm"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="90px"
        size="small"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="pwdForm.newPassword"
            show-password
            placeholder="6~20位，区分大小写"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="pwdForm.confirmPassword"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="small" @click="showPwdDlg = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitPwd"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/userApi";

import { getToken } from "@/utils/auth";
// import { getProfile, updateProfile, updatePassword } from '@/api/user'
// 上面三行你自己解开，并在 src/api/user.js 里暴露对应方法即可

export default {
  name: "Profile",
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.pwdForm.newPassword) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      uploadHeaders: {
        Authorization: getToken(),
      },
      user: {}, // 当前用户完整信息
      form: {}, // 编辑时临时绑定
      editMode: false, // 是否处于编辑状态
      showPwdDlg: false, // 修改密码弹窗
      pwdForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      pwdRules: {
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
          { validator: validatePass2, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.loadProfile();
  },
  methods: {
    /* 1. 加载当前用户详情 ---------------------------------------------------- */
    async loadProfile() {
      const id = (await userApi.getInfo()).data.userId;

      this.user = (await userApi.getById(id)).data;
    },

    /* 2. 进入编辑 ------------------------------------------------------------ */
    enterEdit() {
      this.editMode = true;
      this.form = { ...this.user }; // 浅拷贝一份，取消时可回退
    },
    cancelEdit() {
      this.editMode = false;
    },

    /* 3. 保存资料 ------------------------------------------------------------ */
    async saveProfile() {
      // const req = { id: this.user.id, ...this.form }
      // await updateProfile(req)
      this.user = { ...this.form }; // 更新视图
      this.editMode = false;

      // 修改用户信息
      userApi.update(this.form).then((resp) => {
        this.$message({
          message: resp.message,
          type: "success",
        });
      });
    },

    /* 4. 头像上传钩子 -------------------------------------------------------- */
    beforeAvatarUpload(file) {
      const isImg = ["image/jpeg", "image/png", "image/gif"].includes(
        file.type
      );
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImg) this.$message.error("仅支持 JPG/PNG/GIF 格式!");
      if (!isLt2M) this.$message.error("头像大小不能超过 2MB!");
      return isImg && isLt2M;
    },
    handleAvatarSuccess(res) {
      // http://localhost:9999/file/download?name=4b110c30-b471-4926-a793-553832c08ea2.jpg
      this.user.avatar = this.$baseUrl + "/file/download?name=" + res.message;
      const u = {
        id: this.user.id,
        avatar: this.user.avatar,
      };
      // 修改
      userApi.updateAvatar(u).then((resp) => {
        this.$message.success(resp.message);
      });
    },

    /* 5. 修改密码 ------------------------------------------------------------ */
    submitPwd() {
      this.$refs.pwdForm.validate(async (valid) => {
        if (!valid) return;
        this.showPwdDlg = false;

        const u = {
          id: this.user.id,
          password: this.pwdForm.newPassword,
        };

        userApi.updatePass(u).then((res) => {
          this.$message({
            message: res.message,
            type: "success",
          });
          this.$store.dispatch("user/logout");
          this.$router.push(`/login?redirect=${this.$route.fullPath}`);
        });
      });
    },
    resetPwdForm() {
      this.$refs.pwdForm && this.$refs.pwdForm.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  line-height: 120px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
}
</style>
